<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

// Check to ensure this file is included in Joomla!
defined ( '_JEXEC' ) or die ( 'Restricted access' );

jimport ( 'joomla.application.component.controller' );

class JobBoardControllerJAUserRegister extends JobBoardController {
	/**
	 * Method to display a view
	 *
	 * @access	public
	 * @since	1.5
	 */
	function display() {
		
		$user = JFactory::getUser ();
		if ($user->id)
			$this->setRedirect ( 'index.php' );
		parent::display ();
	}
	
	function cancel() {
		$this->setRedirect ( 'index.php' );
	}
	
	function login($username, $password) {
		// Check for request forgeries
		JRequest::checkToken ( 'request' ) or jexit ( 'Invalid Token' );
		
		global $mainframe;
		
		if ($return = JRequest::getVar ( 'return', '', 'method', 'base64' )) {
			$return = base64_decode ( $return );
			if (! JURI::isInternal ( $return )) {
				$return = '';
			}
		}
		
		$options = array ();
		$options ['remember'] = JRequest::getBool ( 'remember', false );
		$options ['return'] = $return;
		
		$credentials = array ();
		$credentials ['username'] = $username; //JRequest::getVar('username', '', 'method', 'username');
		$credentials ['password'] = $password; //JRequest::getString('passwd', '', 'post', JREQUEST_ALLOWRAW);
		

		//preform the login action
		$error = $mainframe->login ( $credentials, $options );
	
	}
	
	function register() {
		$usersConfig = &JComponentHelper::getParams ( 'com_users' );
		if (! $usersConfig->get ( 'allowUserRegistration' )) {
			JError::raiseError ( 403, JText::_ ( 'Access Forbidden' ) );
			return;
		}
		
		$user = & JFactory::getUser ();
		
		if ($user->get ( 'guest' )) {
			JRequest::setVar ( 'view', 'register' );
		} else {
			$this->setredirect ( 'index.php?option=com_user&task=edit', JText::_ ( 'You are already registered.' ) );
		}
		
		parent::display ();
	}
	
	/**
	 * Save user registration and notify users and admins if required
	 * @return void
	 */
	function register_save($jbusertype='') {
		global $mainframe;
		
		// Check for request forgeries
		JRequest::checkToken () or jexit ( 'Invalid Token' );
		
		// Get required system objects
		$user = clone (JFactory::getUser ());
		$pathway = & $mainframe->getPathway ();
		$config = & JFactory::getConfig ();
		$authorize = & JFactory::getACL ();
		$document = & JFactory::getDocument ();
		
		// If user registration is not allowed, show 403 not authorized.
		$usersConfig = &JComponentHelper::getParams ( 'com_users' );
		if ($usersConfig->get ( 'allowUserRegistration' ) == '0') {
			JError::raiseError ( 403, JText::_ ( 'Access Forbidden' ) );
			return;
		}
		
		// Initialize new usertype setting
		$newUsertype = $usersConfig->get ( 'new_usertype' );
		if (! $newUsertype) {
			$newUsertype = 'Registered';
		}
		
		// Bind the post array to the user object
		if (! $user->bind ( JRequest::get ( 'post' ), 'usertype' )) {
			JError::raiseError ( 500, $user->getError () );
		}
		
		// Set some initial user values
		$user->set ( 'id', 0 );
		$user->set ( 'usertype', $newUsertype );
		$user->set ( 'gid', $authorize->get_group_id ( '', $newUsertype, 'ARO' ) );
		$params = JRequest::getVar('params');
		
		$jconfig = new JConfig();
		$timezone = JRequest::getVar('timezone', $jconfig->offset);
		$user->setParam('timezone', $timezone);
		$user->setParam('usertype', $jbusertype);
		// Set account type
		//		$user->setParam("AccountType",JRequest::getVar('accountType'));
		

		$date = & JFactory::getDate ();
		$user->set ( 'registerDate', $date->toMySQL () );
		
		// If user activation is turned on, we need to set the activation information
		$useractivation = $usersConfig->get ( 'useractivation' );
		if ($useractivation == '1') {
			jimport ( 'joomla.user.helper' );
			$user->set ( 'activation', JUtility::getHash ( JUserHelper::genRandomPassword () ) );
			$user->set ( 'block', '1' );
		}
		
		// If there was an error with registration, set the message and display form
		if (! $user->save ()) {
			JError::raiseWarning('', JText::_( $user->getError()));
			//			$this->register();
			return false;
		} else {
			
			// Send registration confirmation mail
			$password = JRequest::getString ( 'password', '', 'post', JREQUEST_ALLOWRAW );
			$password = preg_replace ( '/[\x00-\x1F\x7F]/', '', $password ); //Disallow control chars in the email
			JobBoardControllerJAUserRegister::_sendMail ( $user, $password );
			// Everything went fine, set relevant message depending upon user activation state and display message
			if ($useractivation == 1) {
				//			$message  = JText::_( 'REG_COMPLETE_ACTIVATE' );
				return $user;
			} else {
				//			$message = JText::_( 'REG_COMPLETE' );
				

				return $user;
			}
		}
		
	//		$this->setRedirect('index.php', $message);
	}
	
	function _sendMail(&$user, $password) {
		global $mainframe;
		
		$db = & JFactory::getDBO ();
		
		$name = $user->get ( 'name' );
		$email = $user->get ( 'email' );
		$username = $user->get ( 'username' );
		
		$usersConfig = &JComponentHelper::getParams ( 'com_users' );
		$sitename = $mainframe->getCfg ( 'sitename' );
		$useractivation = $usersConfig->get ( 'useractivation' );
		$mailfrom = $mainframe->getCfg ( 'mailfrom' );
		$fromname = $mainframe->getCfg ( 'fromname' );
		$siteURL = JURI::base ();
		
		$subject = sprintf ( JText::_ ( 'Account details for' ), $name, $sitename );
		$subject = html_entity_decode ( $subject, ENT_QUOTES );
		
		if ($useractivation == 1) {
			$message = sprintf ( JText::_ ( 'SEND_MSG_ACTIVATE' ), $name, $sitename, $siteURL . "index.php?option=com_user&task=activate&activation=" . $user->get ( 'activation' ), $siteURL, $username, $password );
		} else {
			$message = sprintf ( JText::_ ( 'SEND_MSG' ), $name, $sitename, $siteURL );
		}
		
		$message = html_entity_decode ( $message, ENT_QUOTES );
		
		//get all super administrator
		$query = 'SELECT name, email, sendEmail' . ' FROM #__users' . ' WHERE LOWER( usertype ) = "super administrator"';
		$db->setQuery ( $query );
		$rows = $db->loadObjectList ();
		
		// Send email to user
		if (! $mailfrom || ! $fromname) {
			$fromname = $rows [0]->name;
			$mailfrom = $rows [0]->email;
		}
		
		JUtility::sendMail ( $mailfrom, $fromname, $email, $subject, $message );
		
		// Send notification to all administrators
		$subject2 = sprintf ( JText::_ ( 'Account details for' ), $name, $sitename );
		$subject2 = html_entity_decode ( $subject2, ENT_QUOTES );
		
		// get superadministrators id
		foreach ( $rows as $row ) {
			if ($row->sendEmail) {
				$message2 = sprintf ( JText::_ ( 'SEND_MSG_ADMIN' ), $row->name, $sitename, $name, $email, $username );
				$message2 = html_entity_decode ( $message2, ENT_QUOTES );
				JUtility::sendMail ( $mailfrom, $fromname, $row->email, $subject2, $message2 );
			}
		}
	}
	
	function validatecaptchaaddnew($arg){
		$captcha = new jacapcha();
		$captcha->text_entered = $arg;
		$captcha->validateText("addnew");
		if($captcha->valid_text){
			return true;
		}else{
			return false;
		}
	}
	
	function getPageAfterRegister($type){
		$currentSession = JSession::getInstance('none',array());
        $currentSession->set("jajobboard_menu_redirect", 1);
		// Load JaJobBoard Menu Module config
		jimport( 'joomla.application.module.helper' );
		$modules = JModuleHelper::getModule("jajobboard_menu");
		$url = JRoute::_("index.php");
		if(isset($modules->params)){
			$params = new JParameter ( $modules->params );
			if ( $params->get($type, 0) ){
				$menu =& JSite::getMenu();
				$item = $menu->getItem( $params->get($type, 0) );
				$url = JRoute::_($item->link.'&Itemid='.$params->get($type, 0), false);
			}
		}
		return $url;
	}
	
	function register_resume_save() {
		global $jbconfig;
		$usersConfig = &JComponentHelper::getParams ( 'com_users' );
		$useractivation = $usersConfig->get ( 'useractivation' );
		$succ = true;
		require_once JPATH_COMPONENT_SITE . DS . 'models' . DS . 'jaresumes.php';
		$step = JRequest::getVar ( 'step', '' );
		($step == 'done') or JRequest::checkToken () or jexit ( 'Invalid Token' );
		
		$Itemid = JRequest::getVar ( 'Itemid' );
		
		if ($jbconfig['account']->get('enable_verify_code', 0)){
			$captcha = JRequest::getVar ( 'security_text', '' );
			if(!$this->validatecaptchaaddnew($captcha)){
				JError::raiseWarning(0,JText::_('Security code is incorrect.'));
				JRequest::setVar ( 'postback', true );
				$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
				JRequest::set ( $post, 'request' );
				parent::display ();
				return ;
			}
		}
		
		$resume_model = new JobBoardModelJAResumes ( );
		if (! ($temp_resume = $resume_model->checkData ()))
			$succ = false;
		else {
			if (! $user = $this->register_save ('Job Seeker User'))
				$succ = false;
			else {
				JRequest::setVar ( 'user_id', $user->id );
				$temp_resume->user_id = $user->id;
				$resume_model->setState ( 'request', $temp_resume );
				$rc = $resume_model->store (false);
				if ($rc) {
//					$resume_model->jobSeekerMailSignUp ( $temp_resume->id );
					prepare_data ( 'Job Seeker User', $user->id );
					initial_jobseeker ( $user->id );
					
					$Itemid = get_Itemid(array('option'=>'com_jajobboard', 'view'=>'jajobs'));
									
					if ($jbconfig ['account']->get ( 'ca_needs_approved' ) == 0) {
						$msg = JText::_ ( 'Successfully updated your resume details' ) . '<br/>' . JText::_ ( 'Please use the services of the system' );
						if ($user->block == 0){
							$this->login ( $user->username, $user->password_clear );							
							$Itemid = get_Itemid(array('option'=>'com_jajobboard', 'view'=>'jaresumes', "layout"=>"jaview"));
							
							$this->setRedirect ( $this->getPageAfterRegister("jseeker_register"), $msg );
						}else{
						    $this->setRedirect ( $this->getPageAfterRegister("jseeker_register"), JText::_("REG_COMPLETE_ACTIVATE") );
						    return ;
						}				
					} else {
						if ($user->block == 0){
							$msg = JText::_ ( 'Successfully updated your resume details' ) . '<br/>' . JText::_ ( 'Please wait for admin approval before you can perform other activities as a job seeker' );
							$this->setRedirect ( $this->getPageAfterRegister("jseeker_register"), $msg );	
						}else{
							$this->setRedirect ( $this->getPageAfterRegister("jseeker_register"), JText::_("REG_COMPLETE_ACTIVATE") );
							return ;
						}
					}
				} else {
					$succ = false;
				
				}
			}
		}
		if (! $succ) {
			JRequest::setVar ( 'postback', true );
			$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
			JRequest::set ( $post, 'request' );
			parent::display ();
		}
	}
	
	function register_profile_save() {
		global $jbconfig, $mainframe;
		$succ = true;
		require_once JPATH_COMPONENT_SITE . DS . 'models' . DS . 'japrofiles.php';
		$step = JRequest::getVar ( 'step', '' );
		($step == 'done') or JRequest::checkToken () or jexit ( 'Invalid Token' );
		
		if ($jbconfig['account']->get('enable_verify_code', 0)){
			$captcha = JRequest::getVar ( 'security_text', '' );
			if(!$this->validatecaptchaaddnew($captcha)){
				JError::raiseWarning(0,JText::_('Security code is incorrect.'));
				JRequest::setVar ( 'postback', true );
				$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
				JRequest::set ( $post, 'request' );
				parent::display ();
				return ;
			}
		}
		
		$Itemid = JRequest::getVar ( 'Itemid' );
		$profile_model = new JobBoardModelJAProfiles ( );
		if (! ($temp_profile = $profile_model->checkData ()))
			$succ = false;
		else {
			/* Register user of the Joomla */
			if (! $user = $this->register_save ('Employer User')){
				$succ = false;
			}
			else {
				JRequest::setVar ( 'user_id', $user->id );
				$temp_profile->user_id = $user->id;
				
				/* Save profile of Employer */
				$rc = $temp_profile->store ( false );
				
				if ($rc) {
					/* Send mail for user about profile detail */					
//					$profile_model->EmployerMailSignUp ( $temp_profile->id, $user );
					
					prepare_data ( 'Employer User', $user->id );
					initial_employer ( $user->id );
					
					$Itemid = get_Itemid(array('option'=>'com_jajobboard', 'view'=>'jajobs'));
					
					if ($jbconfig ['account']->get ( 'em_needs_approved' ) == 0) {
						
						$msg = JText::_ ( 'Successfully updated your profile details' ) . '<br/>' . JText::_ ( 'Please use the services of the system.' );
						if ($user->block == 0){
							$this->login ( $user->username, $user->password_clear );
						  $Itemid = get_Itemid(array('option'=>'com_jajobboard', 'view'=>'japrofiles', "layout"=>"jaview"));
						  $this->setRedirect ( $this->getPageAfterRegister("epl_register"), $msg );
						}else{
						    $this->setRedirect ( $this->getPageAfterRegister("epl_register"), JText::_("REG_COMPLETE_ACTIVATE") );
						    return ;
						}
					} else {
						if ($user->block == 0){
							$msg = JText::_ ( 'Successfully updated your profile details' ) . '<br/>' . JText::_ ( 'Please wait for admin approval before you can perform other activities as an employer' );
							$this->setRedirect ( $this->getPageAfterRegister("epl_register"), $msg );
						}else{
							$this->setRedirect ( $this->getPageAfterRegister("epl_register"), JText::_("REG_COMPLETE_ACTIVATE") );
						    return ;
						}
					}				
				} else {					
					$succ = false;
				}
			}
		}
		if (! $succ) {
			JRequest::setVar ( 'postback', true );
			$post = JRequest::get ( 'request', JREQUEST_ALLOWHTML );
			JRequest::set ( $post, 'request' );
			parent::display ();
		}
	}
}
?>
